package com.alibaba.citrus.ots.platform.enhance.repository.impl;

import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.platform.enhance.repository.CustomerAddressRepository;
import com.alibaba.citrus.ots.platform.enhance.repository.CustomerRepository;
import com.alibaba.citrus.ots.platform.enhance.repository.ScItemGroupRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.*;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.UnifiedInventoryService;
import com.epoch.app.otsplatformenhance.channel.service.ChannelService;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.BatchQueryRequest;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.BatchQueryResponse;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.LoadCustomerAddresRequest;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.LoadCustomerAddressRequest;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.PageQueryCustomerAddressDataRequest;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.PageQueryCustomerAddressDataResponse;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.QueryAddressPrincipalCountRequest;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.QueryAddressPrincipalCountResponse;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.QueryAddressPrincipalRequest;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.QueryAddressPrincipalResponse;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.UpdateCustomerAddressResponse;
import com.epoch.app.otsplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.otsplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.otsplatformenhance.domain.scitemgroup.dto.LoadScItemGroupListRequest;
import com.epoch.app.otsplatformenhance.domain.scitemgroup.model.ScItemGroup;
import com.epoch.app.otsplatformenhance.domain.scitemgroup.service.ScItemGroupService;
import com.epoch.app.otsplatformenhance.dto.feature.FullOrganizationValue;
import com.epoch.app.otsplatformenhance.dto.request.CustomerAddressBatchRequest;
import com.epoch.app.otsplatformenhance.dto.request.CustomerAddressRequest;
import com.epoch.app.otsplatformenhance.dto.request.CustomerBatchRequest;
import com.epoch.app.otsplatformenhance.dto.request.QueryAddressRequest;
import com.epoch.app.otsplatformenhance.dto.request.QueryScItemGroupRequest;
import com.epoch.app.otsplatformenhance.enums.CommOperateTypeEnum;
import com.epoch.app.otsplatformenhance.model.dto.ChannelResponse;
import com.epoch.app.otsplatformenhance.model.dto.CustomerAddressIndex;
import com.epoch.app.otsplatformenhance.model.dto.QueryChannelRequest;
import com.epoch.app.otsplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListRequest;
import com.epoch.app.otsplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListResponse;
import com.epoch.app.otsplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListWithPrincipalRequest;
import com.epoch.app.otsplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListWithPrincipalResponse;
import com.epoch.app.otsplatformenhance.opecustomeraddressindex.service.OpeCustomerAddressIndexService;
import com.epoch.app.otsplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.otsplatformenhance.sdo.CustomerSDO;
import com.epoch.app.otsplatformenhance.sdo.ScItemGroupSDO;
import com.epoch.app.otspricecenter.model.dto.CustomerItemPriceRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class CustomerAddressRepositoryImpl implements CustomerAddressRepository {
    private static final Log log = Log.getLogger(CustomerAddressRepositoryImpl.class);

    @Resource
    CustomerAddressService customerAddressService;

    @Resource
    ScItemGroupRepository scItemGroupRepository;

    @Resource
    ChannelService channelService;

    @Resource
    ScItemGroupService scItemGroupService;

    @Resource
    private OpeCustomerAddressIndexService addressIndexService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private UnifiedInventoryService unifiedInventoryService;

    @Resource
    private CustomerRepository customerRepository;


    @Override
    public Boolean editAddress(CustomerAddressSDO addressSDO) {
        CustomerAddress request = new CustomerAddress();
        BeanUtils.copyProperties(addressSDO, request);
        Set<String> platform = new HashSet<>();
        if (StringUtils.isNotBlank(addressSDO.getCommercePlatform())) {
            List<PlatformSDO> queryPlatforms1 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(addressSDO.getCommercePlatform())).build()).getResult();
            if (CollectionUtils.isNotEmpty(queryPlatforms1)) {
                for (PlatformSDO platformSDO : queryPlatforms1) {
                    platform.add(platformSDO.getPlatformName());
                }
            }
            //判断传入的是否是页面回显的中文
            if (platform.contains(addressSDO.getCommercePlatform())) {
                List<PlatformSDO> queryPlatforms2 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformNames(Lists.newArrayList(addressSDO.getCommercePlatform())).build()).getResult();
                String platformCode1 = queryPlatforms2.get(0).getPlatformCode();
                request.setCommercePlatform(platformCode1);
            } else {
                //如果不包含说明传入的重选的id  那么就根据id去查询就可以
                List<PlatformSDO> queryPlatforms3 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(addressSDO.getCommercePlatform())).build()).getResult();
                String platformCode2 = queryPlatforms3.get(0).getPlatformCode();
                request.setCommercePlatform(platformCode2);
            }
        } else {
            //如果在编辑的时候 把电商平台去除了 那么就滞空进行修改
            request.setCommercePlatform("");
        }

        //如果在分派或导入时  负责人为空 则置为空值 进行修改
        if (StringUtils.isBlank(addressSDO.getPrincipal())) {
            request.setPrincipal("");
        }
        request.setId(Long.parseLong(addressSDO.getId()));
        request.setUpdater(addressSDO.getUpdater());
        request.setGmtModified(new Date());
        Integer count = 0;
        try {
            UpdateCustomerAddressResponse response = customerAddressService.updateCustomerAddress(request);
            count = response.getCount();
            if (count == 0) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据更新失败");
        }
        return true;
    }


    @Override
    public CustomerAddressSDO query(CustomerAddressRequest customerAddressRequest) {
        LoadCustomerAddressRequest loadRequest = new LoadCustomerAddressRequest();
        BeanUtils.copyProperties(customerAddressRequest, loadRequest);
        CustomerAddress customerAddress = customerAddressService.loadCustomerAddress(loadRequest);
        CustomerAddressSDO customerAddressSDO = new CustomerAddressSDO();
        BeanUtils.copyProperties(customerAddress, customerAddressSDO);
        CustomerAddressSDO addressSDO = setAddressDetailInfo(customerAddressSDO);
        return addressSDO;
    }

    @NotNull
    private CustomerAddressSDO setAddressDetailInfo(CustomerAddressSDO customerAddressSDO) {
        String channelName = "";
        String itemGroupName = "";
        String shippingConditions = "";
        String frozenStatus = "";
        String kunn2 = "";
        String storeHouse = "";
        String parvw = "";
        String transportAreaName = "";
        String regio = "";
        String customerGroup = "";
        String outOrgSalesDepartmentName = "";
        String storeHouseName = "";
        if (!StringUtils.isEmpty(customerAddressSDO.getFeatures())) {
            JSONObject jsonobject = JSONObject.parseObject(customerAddressSDO.getFeatures());
            channelName = jsonobject.getString("channelName");
            itemGroupName = jsonobject.getString("itemGroupName");
            shippingConditions = jsonobject.getString("shippingConditions");
            frozenStatus = jsonobject.getString("frozenStatus");
            kunn2 = jsonobject.getString("kunn2");
            storeHouse = jsonobject.getString("storeHouse");
            parvw = jsonobject.getString("parvw");
            transportAreaName = jsonobject.getString("transportAreaName");
            regio = jsonobject.getString("regio");
            customerGroup = jsonobject.getString("customerGroup");
            outOrgSalesDepartmentName = jsonobject.getString("outOrgSalesDepartmentName");
            storeHouseName = jsonobject.getString("storeHouseName");
        }

        customerAddressSDO.setChannelName(channelName);
        customerAddressSDO.setItemGroupName(itemGroupName);
        customerAddressSDO.setTransportAreaName(transportAreaName);
        if (Objects.isNull(customerAddressSDO.getStatus())) {
            frozenStatus = "禁用";
        } else {
            frozenStatus = customerAddressSDO.getStatus() == 1 ? "启用" : "禁用";
        }
        customerAddressSDO.setFrozenStatus(frozenStatus);
        customerAddressSDO.setShippingConditions(shippingConditions);
        customerAddressSDO.setKunn2(kunn2);
        customerAddressSDO.setStoreHouse(storeHouse);
        customerAddressSDO.setParvw(parvw);
        customerAddressSDO.setRegio(regio);
        customerAddressSDO.setCustomerGroup(customerGroup);
        customerAddressSDO.setOutOrgSalesDepartmentName(outOrgSalesDepartmentName);
        //取渠道名称
        QueryChannelRequest queryChannelRequest = new QueryChannelRequest();
        queryChannelRequest.setChannelCode(customerAddressSDO.getChannelCode());
        Result<ChannelResponse> channelDetail = channelService.queryChannelDetail(queryChannelRequest);
        if (Objects.nonNull(channelDetail) && Objects.nonNull(channelDetail.getResult())) {
            ChannelResponse detailResult = channelDetail.getResult();
            customerAddressSDO.setChannelName(detailResult.getChannelName());
        }
        //取货品组名称
        LoadScItemGroupListRequest listRequest = new LoadScItemGroupListRequest();
        listRequest.setOutCode(customerAddressSDO.getItemGroup());
        Result<List<ScItemGroup>> listResult = scItemGroupService.loadScItemGroupList(listRequest);
        if (CollectionUtils.isNotEmpty(listResult.getResult())) {
            ScItemGroup group = listResult.getResult().stream().findFirst().get();
            customerAddressSDO.setItemGroupName(group.getName());
        }

        //取仓库名称
        if (org.apache.commons.lang3.StringUtils.isNotBlank(storeHouseName)) {
            customerAddressSDO.setStoreHouseName(storeHouseName);
        } else {
            WmsQueryWarehouseZoneListRequest warehouseZoneListRequest = WmsQueryWarehouseZoneListRequest.builder().code(storeHouse).build();
            WmsQueryWarehouseZoneListResponse zoneListResponse = unifiedInventoryService.wmsQueryWarehouseZoneList(warehouseZoneListRequest);
            if (Objects.nonNull(zoneListResponse) && CollectionUtils.isNotEmpty(zoneListResponse.getResult())) {
                WarehouseInfo warehouseInfo = zoneListResponse.getResult().stream().findFirst().get();
                customerAddressSDO.setStoreHouseName(warehouseInfo.getName());
            }

        }
        return customerAddressSDO;
    }

    @Override
    @RepositoryInvoker
    public PageResult<List<CustomerAddressSDO>> pageQuery(QueryAddressRequest request) {
        PageQueryCustomerAddressListResponse pageQueryCustomerAddressListResponse = new PageQueryCustomerAddressListResponse();
        if (Boolean.TRUE.equals(request.getIsWithPrincipal())) {
            PageQueryCustomerAddressListWithPrincipalRequest customerAddressListRequest = new PageQueryCustomerAddressListWithPrincipalRequest();
            BeanUtils.copyProperties(request, customerAddressListRequest);
            if (Objects.nonNull(request.getId())) {
                customerAddressListRequest.setId(Integer.parseInt(request.getId()));
            }
            if (com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils.isNotBlank(request.getCommercePlatform())){
                List<PlatformSDO> result = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(request.getCommercePlatform())).build()).getResult();
                if (CollectionUtils.isNotEmpty(result)){
                    for (PlatformSDO platformSDO : result) {
                        customerAddressListRequest.setCommercePlatform(platformSDO.getPlatformCode());
                    }
                }
            }
            PageQueryCustomerAddressListWithPrincipalResponse response = addressIndexService.pageQueryCustomerAddressListWithPrincipal(customerAddressListRequest);
            if (null != response) {
                pageQueryCustomerAddressListResponse.setResult(response.getResult());
                pageQueryCustomerAddressListResponse.setTotal(response.getTotal());
                pageQueryCustomerAddressListResponse.setSuccess(response.getSuccess());
            }
        } else {
            PageQueryCustomerAddressListRequest customerAddressListRequest = new PageQueryCustomerAddressListRequest();
            BeanUtils.copyProperties(request, customerAddressListRequest);
            if (Objects.nonNull(request.getId())) {
                customerAddressListRequest.setId(Integer.parseInt(request.getId()));
            }
            if (com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils.isNotBlank(request.getCommercePlatform())){
                List<PlatformSDO> result = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(request.getCommercePlatform())).build()).getResult();
                if (CollectionUtils.isNotEmpty(result)){
                    for (PlatformSDO platformSDO : result) {
                        customerAddressListRequest.setCommercePlatform(platformSDO.getPlatformCode());
                    }
                }
            }
            pageQueryCustomerAddressListResponse = addressIndexService.pageQueryCustomerAddressList(customerAddressListRequest);
        }
        if (Objects.isNull(pageQueryCustomerAddressListResponse) || CollectionUtils.isEmpty(pageQueryCustomerAddressListResponse.getResult())) {
            return PageResult.of(Lists.newArrayList(), 0);
        }
        List<CustomerAddressIndex> customerAddressIndexList = pageQueryCustomerAddressListResponse.getResult();
        Set<String> persons = customerAddressIndexList.stream().map(CustomerAddressIndex::getPrincipal).collect(Collectors.toSet());
        Set<String> orgCodes = customerAddressIndexList.stream().map(CustomerAddressIndex::getOrgSaleOrganizationCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> salesChannelCodes = customerAddressIndexList.stream().map(CustomerAddressIndex::getOrgSaleChannelCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> departCodes = customerAddressIndexList.stream().map(CustomerAddressIndex::getOrgSaleDepartmentCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        HashSet<Object> codes = Sets.newHashSet();
        codes.addAll(orgCodes);
        codes.addAll(salesChannelCodes);
        codes.addAll(departCodes);
        BaselineGetOrganizationByIdsAllRequest byIds2Request = BaselineGetOrganizationByIdsAllRequest.builder().ids(Lists.newArrayList(codes)).build();
        BaselineGetOrganizationByIdsAllResponse byIds2Response = baseDataService.baselineGetOrganizationByIdsAll(byIds2Request);
        Map<String, OrganizationSDO> organizationSDOMap = Maps.newHashMap();
        if (Objects.nonNull(byIds2Response) && CollectionUtils.isNotEmpty(byIds2Response.getResult())) {
            organizationSDOMap = byIds2Response.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));
        }
        Set<String> creators = customerAddressIndexList.stream().map(it -> it.getCreator().replace("CZ_", "")).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> updaters = customerAddressIndexList.stream().map(it -> it.getUpdater().replace("CZ_", "")).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> channelCodeSets = customerAddressIndexList.stream().map(CustomerAddressIndex::getChannelCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        persons.addAll(creators);
        persons.addAll(updaters);
        BaselineGetEmployeeByIdsRequest byIdsRequest = BaselineGetEmployeeByIdsRequest.builder().employeeIdList(Lists.newArrayList(persons)).build();
        Result<List<EmployeeSDO>> listResult = baseDataService.baselineGetEmployeeByIds(byIdsRequest);
        Map<String, EmployeeSDO> employeeSDOMap = Maps.newHashMap();
        if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
            List<EmployeeSDO> employeeSDOS = listResult.getResult();
            employeeSDOMap = employeeSDOS.stream().collect(Collectors.toMap(EmployeeSDO::getId, o -> o));
        }
        Map<String, String> channelMap = Maps.newHashMap();
        BaselineBatchQueryChannelsRequest channelsRequest = BaselineBatchQueryChannelsRequest.builder().channelCodes(Lists.newArrayList(channelCodeSets)).build();
        Map queryChannels = (Map) baseDataService.baselineBatchQueryChannels(channelsRequest);
        if (Objects.nonNull(queryChannels)) {
            Map result = (Map) queryChannels.get("result");
            if (Objects.nonNull(result)) {
                List<Map> channels = (List<Map>) result.get("result");
                if (CollectionUtils.isNotEmpty(channels)) {
                    channelMap = channels.stream().collect(Collectors.toMap(it -> (String) it.get("channelCode"), it -> (String) it.get("channelName")));
                }
            }
        }
        Map<String, EmployeeSDO> finalEmployeeSDOMap = employeeSDOMap;
        Map<String, OrganizationSDO> finalOrganizationSDOMap = organizationSDOMap;
        Map<String, String> finalChannelMap = channelMap;
        List<CustomerAddressSDO> resultList = customerAddressIndexList.stream().map(address -> {
//            String channelName = "";
            String itemGroupName = "";
            String shippingConditions = "";
            String frozenStatus = "";
            String kunn2 = "";
            String storeHouse = "";
            String parvw = "";
            String transportAreaName = "";
            String customerGroup = "";
            String transportArea = "";
            String outOrgSalesDepartmentCode = "";
            String outOrgSalesDepartmentName = "";
            String regio = "";
            String outOrgSalesChannelCode = "";
            String outOrgSalesChannelName = "";
            if (!StringUtils.isEmpty(address.getFeatures())) {
                JSONObject jsonobject = JSONObject.parseObject(address.getFeatures());
//                channelName = jsonobject.getString("channelName");
                itemGroupName = jsonobject.getString("itemGroupName");
                shippingConditions = jsonobject.getString("shippingConditions");
                frozenStatus = jsonobject.getString("frozenStatus");
                kunn2 = jsonobject.getString("kunn2");
                storeHouse = jsonobject.getString("storeHouse");
                parvw = jsonobject.getString("parvw");
                transportAreaName = jsonobject.getString("transportAreaName");
                customerGroup = jsonobject.getString("customerGroup");
                transportArea = jsonobject.getString("transportArea");
                outOrgSalesDepartmentCode = jsonobject.getString("outOrgSalesDepartmentCode");
                outOrgSalesDepartmentName = jsonobject.getString("outOrgSalesDepartmentName");
                outOrgSalesChannelCode = jsonobject.getString("outOrgSalesChannelCode");
                outOrgSalesChannelName = jsonobject.getString("outOrgSalesChannelName");
                regio = jsonobject.getString("regio");
            }

            QueryScItemGroupRequest queryScItemGroupRequest = new QueryScItemGroupRequest();

            CustomerAddressSDO addressSDO = new CustomerAddressSDO();
            BeanUtils.copyProperties(address, addressSDO);
            // 获取货品组ID
            QueryScItemGroupRequest build = QueryScItemGroupRequest.newQueryScItemGroupRequestBuilder().code(address.getItemGroup()).build();
            queryScItemGroupRequest.setCode(address.getItemGroup());
            PageResult<List<ScItemGroupSDO>> listPageResult = scItemGroupRepository.pageQueryScItemGroupList(build);

            if (listPageResult != null && listPageResult.getContent().size() > 0) {
                ScItemGroupSDO sdo = listPageResult.getContent().stream().findFirst().get();
                addressSDO.setItemGroupId(sdo.getId());
                addressSDO.setChannelName(sdo.getName());
            }

            addressSDO.setId(address.getId().toString());
            addressSDO.setItemGroupName(itemGroupName);
            addressSDO.setTransportAreaName(transportAreaName);
            addressSDO.setFrozenStatus(frozenStatus);
            addressSDO.setShippingConditions(shippingConditions);
            addressSDO.setKunn2(kunn2);
            addressSDO.setStoreHouse(storeHouse);
            addressSDO.setParvw(parvw);
            addressSDO.setCustomerGroup(customerGroup);
            addressSDO.setTransportArea(transportArea);
            addressSDO.setOutOrgSalesDepartmentCode(outOrgSalesDepartmentCode);
            addressSDO.setOutOrgSalesDepartmentName(outOrgSalesDepartmentName);
            addressSDO.setRegio(regio);
            addressSDO.setGmtCreate(address.getGmt_create());
            addressSDO.setGmtModified(address.getGmt_modified());
            addressSDO.setOutOrgSalesChannelCode(outOrgSalesChannelCode);
            addressSDO.setOutOrgSalesChannelName(outOrgSalesChannelName);
            EmployeeSDO creator = finalEmployeeSDOMap.get(address.getCreator().replace("CZ_", ""));
            if (Objects.nonNull(creator)) {
                addressSDO.setCreatorName(creator.getName());
            }
            EmployeeSDO updater = finalEmployeeSDOMap.get(address.getUpdater().replace("CZ_", ""));
            if (Objects.nonNull(updater)) {
                addressSDO.setUpdaterName(updater.getName());
            }
            OrganizationSDO orgSDO = finalOrganizationSDOMap.get(address.getOrgSaleOrganizationCode());
            if (Objects.nonNull(orgSDO)) {
                addressSDO.setOrgSalesOrganizationName(orgSDO.getName());
            }
            OrganizationSDO channelSDO = finalOrganizationSDOMap.get(address.getOrgSaleChannelCode());
            if (Objects.nonNull(channelSDO)) {
                addressSDO.setOrgSalesChannelName(channelSDO.getName());
            }
            OrganizationSDO departSDO = finalOrganizationSDOMap.get(address.getOrgSaleDepartmentCode());
            if (Objects.nonNull(departSDO)) {
                addressSDO.setOrgSalesDepartmentName(departSDO.getName());
            }
            EmployeeSDO employeeSDO = finalEmployeeSDOMap.get(address.getPrincipal());
            if (Objects.nonNull(employeeSDO)) {
                addressSDO.setPrincipalName(employeeSDO.getName());
            }
            String channelName = finalChannelMap.get(address.getChannelCode());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(channelName)) {
                addressSDO.setChannelName(channelName);
            }
            if (StringUtils.isNotBlank(address.getCommercePlatform())) {
                List<PlatformSDO> platformSDOS = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformCodes(Lists.newArrayList(address.getCommercePlatform())).build()).getResult();
                if (CollectionUtils.isNotEmpty(platformSDOS)) {
                    String platformName = platformSDOS.get(0).getPlatformName();
                    addressSDO.setCommercePlatform(platformName);
                }
            }
            return addressSDO;
        }).collect(Collectors.toList());

        return PageResult.of(resultList, pageQueryCustomerAddressListResponse.getTotal());
    }

    @Override
    @RepositoryInvoker
    public List<CustomerAddressSDO> batchQuery(CustomerAddressBatchRequest request) {
        BatchQueryRequest batchQueryRequest = new BatchQueryRequest();
        BeanUtils.copyProperties(request, batchQueryRequest);
        BatchQueryResponse response = customerAddressService.batchQuery(batchQueryRequest);
        if (response == null || CollectionUtils.isEmpty(response.getResult())) {
            return null;
        }
        List<CustomerAddressSDO> result = Lists.newArrayList();
        List<CustomerAddress> customerAddressList = response.getResult();
        Set<String> codeSet = customerAddressList.stream().map(CustomerAddress::getCustomerCode).collect(Collectors.toSet());
        CustomerBatchRequest customerBatchRequest = new CustomerBatchRequest();
        customerBatchRequest.setCodes(Lists.newArrayList(codeSet));
        List<CustomerSDO> customerSDOS = customerRepository.batchQuery(customerBatchRequest);
        Map<String, CustomerSDO> customerSDOMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(customerSDOS)) {
            customerSDOMap = customerSDOS.stream().collect(Collectors.toMap(CustomerSDO::getCode, o -> o));
        }
        Set<String> orgCodes = customerAddressList.stream().map(CustomerAddress::getOrgSaleOrganizationCode).filter(org.apache.commons.lang3.StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> salesChannelCodes = customerAddressList.stream().map(CustomerAddress::getOrgSaleChannelCode).filter(org.apache.commons.lang3.StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> departCodes = customerAddressList.stream().map(CustomerAddress::getOrgSaleDepartmentCode).filter(org.apache.commons.lang3.StringUtils::isNotBlank).collect(Collectors.toSet());
        HashSet<String> codes = Sets.newHashSet();
        codes.addAll(orgCodes);
        codes.addAll(salesChannelCodes);
        codes.addAll(departCodes);
        BaselineGetOrganizationByIds2Request byIds2Request = BaselineGetOrganizationByIds2Request.builder().ids(Lists.newArrayList(codes)).status(1).build();
        BaselineGetOrganizationByIds2Response byIds2Response = baseDataService.baselineGetOrganizationByIds2(byIds2Request);
        Map<String, OrganizationSDO> organizationSDOMap = Maps.newHashMap();
        if (Objects.nonNull(byIds2Response) && CollectionUtils.isNotEmpty(byIds2Response.getResult())) {
            organizationSDOMap = byIds2Response.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));
        }

        for (CustomerAddress address : customerAddressList) {
            CustomerAddressSDO addressSDO = new CustomerAddressSDO();
            BeanUtils.copyProperties(address, addressSDO);
            addressSDO.setId(String.valueOf(address.getId()));
            CustomerSDO customerSDO = customerSDOMap.get(address.getCustomerCode());
            if (Objects.nonNull(customerSDO)) {
                addressSDO.setCustomerName(customerSDO.getName());
            }
            OrganizationSDO orgSDO = organizationSDOMap.get(address.getOrgSaleOrganizationCode());
            if (Objects.nonNull(orgSDO)) {
                addressSDO.setOrgSalesOrganizationName(orgSDO.getName());
            }
            OrganizationSDO channelSDO = organizationSDOMap.get(address.getOrgSaleChannelCode());
            if (Objects.nonNull(channelSDO)) {
                addressSDO.setOrgSalesChannelName(channelSDO.getName());
            }
            OrganizationSDO departSDO = organizationSDOMap.get(address.getOrgSaleDepartmentCode());
            if (Objects.nonNull(departSDO)) {
                addressSDO.setOrgSalesDepartmentName(departSDO.getName());
            }
            result.add(addressSDO);
        }
        return result;
    }

    @Override
    @RepositoryInvoker
    public Integer queryAddressPrincipalCount(FullOrganizationValue fullOrganizationValue) {
        QueryAddressPrincipalCountRequest request = new QueryAddressPrincipalCountRequest();
        request.setOrgBussinessUnitCode(fullOrganizationValue.getOrgBusinessUnitCode());
        request.setOrgSaleOrganizationCode(fullOrganizationValue.getOrgSalesOrganizationCode());
        request.setOrgSaleChannelCode(fullOrganizationValue.getOrgSalesChannelCode());
        request.setOrgSaleDepartmentCode(fullOrganizationValue.getOrgSalesDepartmentCode());
        QueryAddressPrincipalCountResponse response = customerAddressService.queryAddressPrincipalCount(request);
        if (response != null) {
            return response.getCount();
        }
        return null;
    }

    @Override
    @RepositoryInvoker
    public List<String> queryAddressPrincipalList(FullOrganizationValue fullOrganizationValue) {
        QueryAddressPrincipalRequest request = new QueryAddressPrincipalRequest();
        request.setOrgBussinessUnitCode(fullOrganizationValue.getOrgBusinessUnitCode());
        request.setOrgSaleOrganizationCode(fullOrganizationValue.getOrgSalesOrganizationCode());
        request.setOrgSaleChannelCode(fullOrganizationValue.getOrgSalesChannelCode());
        request.setOrgSaleDepartmentCode(fullOrganizationValue.getOrgSalesDepartmentCode());
        request.setStart(fullOrganizationValue.getStart());
        request.setLimit(fullOrganizationValue.getLimit());

        QueryAddressPrincipalResponse response = customerAddressService.queryAddressPrincipal(request);
        if (response != null) {
            return response.getResult();
        }
        return null;
    }

    @Override
    @RepositoryInvoker
    public CustomerAddressSDO load(String id) {
        LoadCustomerAddresRequest loadRequest = new LoadCustomerAddresRequest();
        loadRequest.setId(id);
        CustomerAddress customerAddress = new CustomerAddress();
        try {
            customerAddress = customerAddressService.loadCustomerAddres(loadRequest);
        } catch (Exception e) {
            return null;
        }
        CustomerAddressSDO customerAddressSDO = new CustomerAddressSDO();
        BeanUtils.copyProperties(customerAddress, customerAddressSDO);
        //电商平台
        queryCommercePlatform(customerAddressSDO);
        customerAddressSDO.setId(String.valueOf(customerAddress.getId()));
        return customerAddressSDO;
    }

    private void queryCommercePlatform(CustomerAddressSDO customerAddressSDO) {
        //根据当前数据的平台Code去获取对应的名称
        if (StringUtils.isNotBlank(customerAddressSDO.getCommercePlatform())) {
            List<PlatformSDO> platformSDOS = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformCodes(Lists.newArrayList(customerAddressSDO.getCommercePlatform())).build()).getResult();
            if (CollectionUtils.isNotEmpty(platformSDOS)) {
                String platformName = platformSDOS.get(0).getPlatformName();
                customerAddressSDO.setCommercePlatform(platformName);
            }
        }
       /* try{
        BaselineGetOrganizationByIdsAllRequest byIdsAllRequest = new BaselineGetOrganizationByIdsAllRequest();
        if (StringUtils.isBlank(customerAddressSDO.getOrgSaleDepartmentCode())){
            return;
        }
        byIdsAllRequest.setIds(Lists.newArrayList(customerAddressSDO.getOrgSaleDepartmentCode()));
        List<OrganizationSDO> result = baseDataService.baselineGetOrganizationByIdsAll(byIdsAllRequest).getResult();
        if (CollectionUtils.isEmpty(result)){
            log.info("queryCommercePlatform"+customerAddressSDO.getOrgSaleDepartmentCode());
            return;
        }
        Set<String> platformId = result.stream().map(OrganizationSDO::getPlatformId).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        BaselineBatchQueryPlatforms2Request platforms2Request = new BaselineBatchQueryPlatforms2Request();
        platforms2Request.setPlatformIds(Lists.newArrayList(platformId));
        List<PlatformSDO> platformSDOS = baseDataService.baselineBatchQueryPlatforms2(platforms2Request).getResult();
        platformSDOS.stream().forEach(it->{
            customerAddressSDO.setCommercePlatform(it.getPlatformName());
        });
        }catch (Exception e){
            log.error("queryCommercePlatform失败");
            return;
        }*/
    }


    public Result<List<CustomerAddress>> pageQueryCustomerAddressData(CustomerItemPriceRequest customerItemPriceRequest) {
        PageQueryCustomerAddressDataRequest addressDataRequest = new PageQueryCustomerAddressDataRequest();
        addressDataRequest.setCustomerAddressCode(customerItemPriceRequest.getCustomerSendCode());
        addressDataRequest.setSalesOrganizationCode(customerItemPriceRequest.getSaleOrganizationCode());
        addressDataRequest.setChannelCode(customerItemPriceRequest.getChannelCode());
        addressDataRequest.setStart(customerItemPriceRequest.getStart());
        addressDataRequest.setLimit(customerItemPriceRequest.getLimit());
        addressDataRequest.setStatus(CommOperateTypeEnum.ENABLE.getCode());
        PageQueryCustomerAddressDataResponse customerAddressDataResponse = customerAddressService.pageQueryCustomerAddressData(addressDataRequest);

        //参数封装
        Result<List<CustomerAddress>> result = Result.success(customerAddressDataResponse.getResult());
        result.setTotal(customerAddressDataResponse.getTotal());
        return result;
    }
}
